package com.satan.fmmall.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPay;
import com.satan.fmmall.config.MyPayConfig;
import com.satan.fmmall.entity.Orders;
import com.satan.fmmall.mapper.OrdersMapper;
import com.satan.fmmall.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrderTimeOutCheck
 * @Description TODO
 * @date 2022/4/20 12:54
 * @Version 1.0
 */
@Component
public class OrderTimeOutCheck {
    @Resource
    private MyPayConfig myPayConfig;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrderService orderService;

    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOrder(){
        //1.查询超过30分钟订单状态仍然为待支付状态的订单
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getStatus,1);
        queryWrapper.lt(Orders::getCreateTime,new Date(System.currentTimeMillis()-30*60*1000));
        List<Orders> ordersList = ordersMapper.selectList(queryWrapper);
//        ordersList.forEach(System.out::println);
        //2.访问微信平台接口确认当前订单的状态是否为已支付
        WXPay wxPay = new WXPay(myPayConfig);
        ordersList.forEach(orders -> {
            HashMap<String,String> params=new HashMap<>();
            params.put("out_trade_no", orders.getOrderId());
            try {
                Map<String, String> resp = wxPay.orderQuery(params);
                //System.out.println(resp);
                //2.1如果订单已经支付，则修改订单状态为“待发货/已支付” status=2
                if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))){
                    Orders updateOrder=new Orders();
                    updateOrder.setOrderId(orders.getOrderId());
                    updateOrder.setStatus("2");
                    ordersMapper.updateById(updateOrder);
                }else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))){
                    //2.2如果确实未支付则取消订单
                    //向微信平台发送请求关闭当前订单的支付链接
                    resp = wxPay.closeOrder(params);
                    if ("SUCCESS".equalsIgnoreCase(resp.get("return_code"))){
                        //关闭订单
                        orderService.closeOrder(orders.getOrderId());
                    }

                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });








    }
}
